package cn.jingyuan.swan.cloud.oauth2;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;

import java.util.HashMap;
import java.util.Map;

/**
 * JwtAccessToken 转换器
 */
public class DefaultTokenEnhancer extends TokenEnhancerChain {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInformation = new HashMap<>(8);
        if (!authentication.isClientOnly()) {
            if (authentication.getPrincipal() != null && authentication.getPrincipal() instanceof DefaultUserDetails) {
                // 设置额外用户信息
                DefaultUserDetails userDetails = ((DefaultUserDetails) authentication.getPrincipal());
                additionalInformation.put(DefaultSecurityConstants.OPEN_ID, userDetails.getUserId());
                // additionalInformation.put(OpenSecurityConstants.DOMAIN, userDetails.getDomain());
            }
        }

        DefaultOAuth2AccessToken defaultAccessToken = new DefaultOAuth2AccessToken(accessToken);
        defaultAccessToken.setAdditionalInformation(additionalInformation);

        return super.enhance(defaultAccessToken, authentication);
    }

}
